package ar.uba.is2.common.threads;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

public class ThreadManager {

	private Logger log = Logger.getLogger(ThreadManager.class);
	private static final boolean DAEMON_THREAD = false;

	private static int ID = 0;

	private Map<String, Thread> threads;
	
	public static final ThreadManager instance = new ThreadManager();
	
	private ThreadManager(){
		this.threads = new HashMap<String, Thread>();
	}
	
	public String crearYCorrerThread(Runnable runnable){
		if ( log.isDebugEnabled() ) {
			log.debug("Creando nuevo Thread");
		}
		if (runnable == null) {
			if ( log.isDebugEnabled() ) {
				log.debug("Descartando Thread. Runnable es null");
			}
			return null;
		}
		String id = runnable.getClass().getSimpleName() + ID++;
		
		Thread thread = new Thread(runnable, id);
		thread.setDaemon(DAEMON_THREAD);
		thread.start();

		if ( log.isDebugEnabled() ) {
			log.debug(String.format("Thread %s creado para la clase %s", id, runnable.getClass()));
		}

		this.threads.put(id, thread);
		
		return id;
	}
	
	public void detenerThread(String id){
		Thread thread = this.threads.get(id);
		
		if (thread != null && !thread.isInterrupted()) {
			thread.interrupt();
		}
	}

	public void detenerTodosLosThread(){
		for (Thread thread : this.threads.values()){
			if (thread != null && !thread.isInterrupted()) {
				thread.interrupt();
			}
		}
	}
}
